#!/bin/bash

help () {
    cat << EOF
Generate unique key for a new balena device
balena-unique-key [options] <key name>

Options:
    -h, --help
        Display this help and exit.

    -c, --config-path CONFIG_PATH
        Use a non default config.json file.
        This argument is passed to balena-config-vars script.
EOF
}

# Parse arguments
while [ $# -gt 0 ]; do
    key=$1
    case $key in
        -h|--help)
            help
            exit 0
            ;;
        -c|--config-path)
            CONFIG_PATH=$2
            shift
            ;;
        *)
            key_name=$1
            ;;
    esac
    shift
done

# shellcheck disable=SC1091
source /usr/sbin/balena-config-vars

if [ -z "$CONFIG_PATH" ]; then
    echo "[ERROR] balena-unique-key : Please set CONFIG_PATH environment variable."
    exit 1
fi

if ! key=$("${CAT}" "${CONFIG_PATH}" | jq -r ".$key_name //empty"); then
    echo "[ERROR] balena-unique-key : Error parsing the CONFIG_PATH json. Is it a valid json?"
    exit 1
fi

if [ -z "$key" ]; then
    echo "[INFO] balena-unique-key: $key_name missing from config file. Generating..."
    if ! key=$(openssl rand -hex 16); then
        echo "[ERROR] balena-unique-key : Failed to generate the random key."
        exit 1
    fi
    "${CAT}" "$CONFIG_PATH" | jq ".$key_name=\"$key\"" | "${WR}" "$CONFIG_PATH"
else
    echo "[INFO] balena-unique-key : Device already has $key_name assigned."
fi

exit 0
